package com.zjj.lbw.spring.security.config;

import com.zjj.lbw.spring.security.handler.MyAuthenticationFailHandler;
import com.zjj.lbw.spring.security.handler.MyAuthenticationSuccessHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.rememberme.JdbcTokenRepositoryImpl;
import org.springframework.security.web.authentication.rememberme.PersistentTokenRepository;

import javax.sql.DataSource;

//@Configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    DataSource dataSource;

    @Bean
    public PasswordEncoder passwordEncoder() {
//        return NoOpPasswordEncoder.getInstance();
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService);
//        auth.inMemoryAuthentication().withUser("admin")
//                .password(passwordEncoder().encode("123"))
//                .authorities("admin");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin(); // 表单登录
//                .loginPage("/login.html")
//                .loginProcessingUrl("/user/login")
//                .defaultSuccessUrl("/main.html")
//                .successForwardUrl("/tomain")
//                .failureForwardUrl("/toerror")
//                .successHandler(new MyAuthenticationSuccessHandler("/main.html"))
//                .failureHandler(new MyAuthenticationFailHandler("/error.html"));

        http.sessionManagement()
                .invalidSessionUrl("/session/invalid")
                .maximumSessions(1)
                .maxSessionsPreventsLogin(false);

        // 授权，配置了 自定义登录，必须配置授权，需要自己控制 哪些请求需要认证
        http.authorizeRequests()
                .antMatchers("/login.html", "/user/login", "/error.html", "/session/invalid").permitAll()
                .anyRequest().authenticated().
                and()
                .csrf().disable();

        //记住我
        http.rememberMe()
                .tokenRepository(persistentTokenRepository())//设置持久化仓库
                .tokenValiditySeconds(3600) //超时时间,单位s 默认两周
                .userDetailsService(userDetailsService); //设置自定义登录逻辑

        // 推出逻辑，下面是默认的配置
        http.logout()
                .logoutUrl("/logout")
                .logoutSuccessUrl("/login.html");
    }

    public PersistentTokenRepository persistentTokenRepository() {
        JdbcTokenRepositoryImpl jdbcTokenRepository = new JdbcTokenRepositoryImpl();
        //设置数据源
        jdbcTokenRepository.setDataSource(dataSource);
        return jdbcTokenRepository;
    }
}
